package com.canbot.u05.activity.free

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import com.alibaba.fastjson.JSON
import com.canbot.u05.R
import com.canbot.u05.activity.BaseActivityNoTitle
import com.canbot.u05.activity.presidemode.eventbus.AudioEvent
import com.canbot.u05.activity.base.BaseMediaSetActivity
import com.canbot.u05.activity.base.BaseVoiceSetActivity
import com.canbot.u05.activity.base.BaseChooseJopActivity
import com.canbot.u05.activity.base.BaseChooseMoreJopActivity
import com.canbot.u05.bean.JsonResponse
import com.canbot.u05.helper.DialogBuildHelper
import com.canbot.u05.socket.IpMsgConst
import com.canbot.u05.utils.OkHttpUtils
import com.canbot.u05.utils.PathConst
import com.canbot.u05.utils.ToastTools
import kotlinx.android.synthetic.main.free_settings.*
import java.io.File
import java.util.*

/**
 * Created by zmp on 2019/6/3 16:57
 * @author zmp
 * 空闲状态设置主界面
 */
class FreeSettingsActivity : BaseActivityNoTitle() {

    private var hintDialog: DialogBuildHelper.TipBuilder? = null
    lateinit var toastTools: ToastTools
    private lateinit var freeSetInfo: FreeSetInfo

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.free_settings)
        toastTools = ToastTools.newInstance(this)
        initView()
        getData()
    }

    private fun getData() {
        showBaseLoadDialog()
        upFree2Service(GET_DATA)
    }

    private fun initView() {
        back_btn_head.setOnClickListener(onClick)
        saveTextView.setOnClickListener(onClick)
        pointRelativeLayout.setOnClickListener(onClick)
        voiceRelativeLayout.setOnClickListener(onClick)
        forwardRelativeLayout.setOnClickListener(onClick)
        mediaRelativeLayout.setOnClickListener(onClick)
        mediaContentRelativeLayout.setOnClickListener(onClick)
        mediaHzRelativeLayout.setOnClickListener(onClick)
        patrolRelativeLayout.setOnClickListener(onClick)
        areaRelativeLayout.setOnClickListener(onClick)
        patrolIntervalRelativeLayout.setOnClickListener(onClick)
        patrolSustainRelativeLayout.setOnClickListener(onClick)


    }

    private val onClick: View.OnClickListener = View.OnClickListener {
        when (it.id) {
            R.id.back_btn_head -> {
                showBackDialog(getString(R.string.task_exit_hint))
            }
            R.id.saveTextView -> {
                upData(freeSetInfo)
            }
            R.id.pointRelativeLayout -> {
                startActivityForResult(Intent(this@FreeSettingsActivity, BaseChooseJopActivity::class.java), JOP_CODE)
            }
            R.id.voiceRelativeLayout -> {
                startActivityForResult(Intent(this@FreeSettingsActivity, BaseVoiceSetActivity::class.java), VOICE_CODE)
            }

            R.id.forwardRelativeLayout -> {
                freeSetInfo.autoForWard = !freeSetInfo.autoForWard
                forwardImageView.isSelected = freeSetInfo.autoForWard
                if (freeSetInfo.autoForWard) {
                    DialogBuildHelper.createHintTipDialog(this)
                            .setTitle(getString(R.string.attention))
                            .setContent(getString(R.string.free_forward_open_hint), Gravity.START)
                            .setClickListener(null, true)
                            .show()
                }
            }

            R.id.mediaRelativeLayout -> {
                freeSetInfo.freeMediaPlay = !freeSetInfo.freeMediaPlay
                mediaImageView.isSelected = freeSetInfo.freeMediaPlay
                mediaContentRelativeLayout.visibility = if (freeSetInfo.freeMediaPlay) View.VISIBLE else View.GONE
                mediaHzRelativeLayout.visibility = if (freeSetInfo.freeMediaPlay) View.VISIBLE else View.GONE
            }

            R.id.mediaContentRelativeLayout -> {
                startActivityForResult(Intent(this@FreeSettingsActivity, BaseMediaSetActivity::class.java), MEDIA_CODE)
            }

            R.id.mediaHzRelativeLayout -> {
                startActivityForResult(Intent(this@FreeSettingsActivity, FreeTimeHzActivity::class.java)
                        .putExtra(FreeTimeHzActivity.TIME_MODE_KEY, FreeTimeHzActivity.TIME_MODE_HZ)
                        .putExtra(FreeTimeHzActivity.RESULT_TIME, freeSetInfo.freeMediaHz?.timeName
                                ?: "1 min/次"), VIDEO_HZ)
            }

            R.id.patrolRelativeLayout -> {
                freeSetInfo.patrolOpen = !freeSetInfo.patrolOpen
                patrolImageView.isSelected = freeSetInfo.patrolOpen
                forwardRelativeLayout.visibility = if (freeSetInfo.patrolOpen) View.VISIBLE else View.GONE
                patrolIntervalRelativeLayout.visibility = if (freeSetInfo.patrolOpen) View.VISIBLE else View.GONE
                if (freeSetInfo.patrolOpen) {
                    patrolSustainRelativeLayout.visibility = View.VISIBLE
                    freeSetInfo.let { freeSetInfo ->
                        if (freeSetInfo.intervalTimeNum() == -1L) {
                            patrolSustainRelativeLayout.visibility = View.GONE
                        }
                    }
                } else {
                    patrolSustainRelativeLayout.visibility = View.GONE
                }
            }

            R.id.areaRelativeLayout -> {
                startActivityForResult(Intent(this@FreeSettingsActivity, BaseChooseMoreJopActivity::class.java), AREA_CODE)
            }
            R.id.patrolIntervalRelativeLayout -> {
                startActivityForResult(Intent(this@FreeSettingsActivity, FreeTimeHzActivity::class.java)
                        .putExtra(FreeTimeHzActivity.TIME_MODE_KEY, FreeTimeHzActivity.TIME_MODE_INTERVAL)
                        .putExtra(FreeTimeHzActivity.RESULT_TIME, freeSetInfo.patrolInterval?.timeName
                                ?: "一直闲逛"), PATROL_INTERVAL)
            }

            R.id.patrolSustainRelativeLayout -> {
                startActivityForResult(Intent(this@FreeSettingsActivity, FreeTimeHzActivity::class.java)
                        .putExtra(FreeTimeHzActivity.TIME_MODE_KEY, FreeTimeHzActivity.TIME_MODE_SUSTAIN)
                        .putExtra(FreeTimeHzActivity.RESULT_TIME, freeSetInfo.patrolSustain?.timeName
                                ?: "5 min"), PATROL_SUSTAIN)

            }
        }
    }

    private fun showBackDialog(content: String) {
        if (hintDialog == null) {
            hintDialog = DialogBuildHelper.createDialogTip(this)
        }
        hintDialog?.setContent(content, Gravity.CENTER)
                ?.setClickListener(object : DialogBuildHelper.ITipClickListener() {
                    override fun sure() {
                        finish()
                    }
                }, true)
        hintDialog?.show()
    }


    private fun upData(freeSetInfo: FreeSetInfo) {
        showBaseLoadDialog()
        val arrList = arrayListOf<AudioEvent>()
        freeSetInfo.freeMediaInfo?.let {
            if (it.mediaType == MediaInfo.AUDIO_TYPE_RECODE) {
                arrList.add(AudioEvent(MediaInfo.AUDIO_TYPE_RECODE, it.mediaContentOrPath, it.simpleName))
            }
        }
        freeSetInfo.voiceInfo?.let {
            if (it.mediaType == MediaInfo.AUDIO_TYPE_RECODE) {
                arrList.add(AudioEvent(MediaInfo.AUDIO_TYPE_RECODE, it.mediaContentOrPath, it.simpleName))
            }
        }
        if (arrList.isEmpty()) {
            upFree2Service(UP_DATA)
        } else {
            upVoice2Head(arrList)
        }
    }

    private fun upVoice2Head(arrList: ArrayList<AudioEvent>) {
        val url = IpMsgConst.HTTP_URL + "guideMapAction"
        val hashMap = HashMap<String, Any>()
        hashMap["type"] = "1"
        hashMap["data"] = JSON.toJSONString(arrList)
        arrList.forEach {
            hashMap[it.musicName] = File(PathConst.ROOT_PATH + it.musicPath)
        }
        OkHttpUtils.upLoadFile(url, hashMap, object : OkHttpUtils.OkHttpCallBack {
            override fun onSuccess(result: String) {
                Log.e(TAG, "upVoice2Head$result")
                toastTools.showText(getString(R.string.up_voice_success))
                upFree2Service(UP_DATA)
            }

            override fun onFailure() {
                dismissBaseDialog()
                toastTools.showText(getString(R.string.service_error_hint))
            }
        })

    }

    private fun upFree2Service(type: Int) {
        val url = IpMsgConst.HTTP_URL_CHEST + "freeSetAction"
        val hashMap = HashMap<String, Any>()
        hashMap["type"] = "$type"
        if (type == UP_DATA) {
            hashMap["data"] = JSON.toJSONString(freeSetInfo)
        }
        OkHttpUtils.upLoadFile(url, hashMap, object : OkHttpUtils.OkHttpCallBack {
            override fun onSuccess(result: String) {
                Log.e(TAG, "upVoice2Head$result")
                dismissBaseDialog()
                if (type == UP_DATA) {
                    finish()
                    toastTools.showText(getString(R.string.upload_complete))
                } else if (type == GET_DATA) {
                    showViewByData(result)
                }
            }

            override fun onFailure() {
                dismissBaseDialog()
                toastTools.showText(getString(R.string.service_error_hint))
                finish()
            }
        })
    }

    private fun showViewByData(result: String) {
        val strMsgBean = JSON.parseObject(result, JsonResponse::class.java)
        if (strMsgBean.rc == 0 && strMsgBean.result != null) {
            try {
                freeSetInfo = JSON.parseObject(strMsgBean.result.toString(), FreeSetInfo::class.java)
                        ?: FreeSetInfo()
                runOnUiThread {
                    showView(freeSetInfo)
                }
            } catch (e: Exception) {
                Log.e(TAG, "showViewByData", e)
            }
        }
    }

    private fun showView(freeSetInfo: FreeSetInfo) {
        pointTextView.text = freeSetInfo.jopPosition
        forwardImageView.isSelected = freeSetInfo.autoForWard
        mediaImageView.isSelected = freeSetInfo.freeMediaPlay
        mediaContentRelativeLayout.visibility = if (freeSetInfo.freeMediaPlay) View.VISIBLE else View.GONE
        mediaHzRelativeLayout.visibility = if (freeSetInfo.freeMediaPlay) View.VISIBLE else View.GONE
        patrolImageView.isSelected = freeSetInfo.patrolOpen
        patrolIntervalRelativeLayout.visibility = if (freeSetInfo.patrolOpen) View.VISIBLE else View.GONE
        if (freeSetInfo.patrolOpen) {
            forwardRelativeLayout.visibility = View.VISIBLE
            patrolSustainRelativeLayout.visibility = View.VISIBLE
            freeSetInfo.let {
                if (it.intervalTimeNum() == -1L) {
                    patrolSustainRelativeLayout.visibility = View.GONE
                }
            }
        } else {
            patrolSustainRelativeLayout.visibility = View.GONE
            forwardRelativeLayout.visibility = View.GONE
        }

        freeSetInfo.voiceInfo?.let {
            voiceTextView.text = it.simpleName
        }
        freeSetInfo.freeMediaInfo?.let {
            mediaTextView.text = it.simpleName
        }
        freeSetInfo.freeMediaHz?.let {
            videoHzTextView.text = it.timeName
        }
        freeSetInfo.patrolInterval?.let {
            patrolIntervalTextView.text = it.timeName
        }
        freeSetInfo.patrolSustain?.let {
            patrolSustainTextView.text = it.timeName
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK && data != null) {
            when (requestCode) {
                JOP_CODE -> {
                    val stringExtra = data.getStringExtra("jopPosition")
                    freeSetInfo.jopPosition = stringExtra
                    pointTextView.text = stringExtra
                }
                VOICE_CODE -> {
                    data.apply {
                        val simpleName = getStringExtra(BaseVoiceSetActivity.AUDIO_SIMPLE_NAME_KEY)
                        val voicePath = getStringExtra(BaseVoiceSetActivity.AUDIO_PATH_OR_CONTENT)
                        val voiceType = getIntExtra(BaseVoiceSetActivity.AUDIO_TYPE_KEY, -1)
                        voiceTextView.text = simpleName
                        freeSetInfo.voiceInfo = MediaInfo(voiceType, simpleName, voicePath)
                    }
                }
                MEDIA_CODE -> {
                    data.apply {
                        val simpleName = getStringExtra(BaseVoiceSetActivity.AUDIO_SIMPLE_NAME_KEY)
                        val voicePath = getStringExtra(BaseVoiceSetActivity.AUDIO_PATH_OR_CONTENT)
                        val voiceType = getIntExtra(BaseVoiceSetActivity.AUDIO_TYPE_KEY, -1)
                        mediaTextView.text = simpleName
                        freeSetInfo.freeMediaInfo = MediaInfo(voiceType, simpleName, voicePath)
                    }
                }
                VIDEO_HZ -> {
                    data.apply {
                        val resultTime = getStringExtra(FreeTimeHzActivity.RESULT_TIME)
                        val resultNum = getLongExtra(FreeTimeHzActivity.RESULT_NUM, -1)
                        videoHzTextView.text = resultTime
                        freeSetInfo.freeMediaHz = FreeTimeInfo(resultTime, resultNum)
                    }
                }
                AREA_CODE -> {
                    data.apply {
                        val points = getStringArrayListExtra("points")
                        freeSetInfo.points = points
                    }
                }
                PATROL_INTERVAL -> {
                    data.apply {
                        val resultTime = getStringExtra(FreeTimeHzActivity.RESULT_TIME)
                        val resultNum = getLongExtra(FreeTimeHzActivity.RESULT_NUM, -1)
                        patrolIntervalTextView.text = resultTime
                        freeSetInfo.patrolInterval = FreeTimeInfo(resultTime, resultNum)

                        if (resultNum == -1L) {
                            patrolSustainRelativeLayout.visibility = View.GONE
                        } else {
                            patrolSustainRelativeLayout.visibility = View.VISIBLE
                        }
                    }
                }
                PATROL_SUSTAIN -> {
                    data.apply {
                        val resultTime = getStringExtra(FreeTimeHzActivity.RESULT_TIME)
                        val resultNum = getLongExtra(FreeTimeHzActivity.RESULT_NUM, -1)
                        patrolSustainTextView.text = resultTime
                        freeSetInfo.patrolSustain = FreeTimeInfo(resultTime, resultNum)
                    }
                }
            }
        } else if (resultCode == BaseMediaSetActivity.SYSTEM_CODE) {
            when (requestCode) {
                VOICE_CODE -> {
                    voiceTextView.text = getString(R.string.system_voice)
                    freeSetInfo.voiceInfo = null
                }
                MEDIA_CODE -> {
                    mediaTextView.text = getString(R.string.system_voice)
                    freeSetInfo.freeMediaInfo = null
                }
            }
        }
    }

    private companion object {
        const val TAG = "FreeSettingsActivity"
        const val JOP_CODE = 1000
        const val VOICE_CODE = 1001
        const val MEDIA_CODE = 1002
        const val VIDEO_HZ = 1003
        const val PATROL_INTERVAL = 1004
        const val PATROL_SUSTAIN = 1005
        const val AREA_CODE = 1006
        const val GET_DATA = 0
        const val UP_DATA = 1
    }
}